package cn.zsb.web;

import cn.zsb.entity.Result;
import org.springframework.validation.BindException;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.validation.ConstraintViolation;
import javax.validation.ConstraintViolationException;

/**
 * @author oldliu
 * @since 1.0
 */
@RestControllerAdvice
public class ZsbHandler {
    @ExceptionHandler(Exception.class)
    public Result exc1(Exception e){
        e.printStackTrace();
        return Result.error(String.valueOf(e));
    }
    ///
    @ExceptionHandler(ConstraintViolationException.class)
    public Result handle(ConstraintViolationException e) {
        StringBuilder sb = new StringBuilder();
        for (ConstraintViolation f : e.getConstraintViolations())
            sb.append(f.getMessage() + "<br/>");
        return Result.error(sb.toString());
    }
    @ExceptionHandler(BindException.class)
    public Result handle(BindException e) {
        StringBuilder sb = new StringBuilder();
        for (ObjectError f : e.getAllErrors())
            sb.append(f.getDefaultMessage()+ "<br/>");
        return Result.error(sb.toString());
    }
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public Result handle(MethodArgumentNotValidException e) {//!!!
        StringBuilder sb = new StringBuilder();
        for (ObjectError f : e.getBindingResult().getAllErrors())
            sb.append(f.getDefaultMessage()+ "<br/>");
        return Result.error(sb.toString());
    }
}
